package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.uduemc.biso.core.utils.UserAgentUtil;
import com.uduemc.biso.node.core.common.entities.surfacedata.bannerdata.Banner;
import com.uduemc.biso.node.core.common.udinpojo.BannerData;
import com.uduemc.biso.node.core.common.udinpojo.banner.BannerDataVideoConfig;
import com.uduemc.biso.node.core.common.udinpojo.banner.BannerImageList;
import com.uduemc.biso.node.core.common.udinpojo.common.ImageConfig;
import com.uduemc.biso.node.core.common.udinpojo.common.LinkConfig;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SBannerItem;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.BannerItemQuote;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SRHeadDynamicSource;
import com.uduemc.biso.node.web.component.SiteUrlComponent;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

@Component
public class HBannerUdin {

	private static String name = "banner";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private SRHeadDynamicSource sRHeadDynamicSource;

	@Autowired
	private HttpServletRequest request;

	// 是否通过 surface 的方式渲染
	static boolean surface = true;

	public StringBuilder html(Banner banner) {

		if (banner == null) {
			// 使用默认banner
			return new StringBuilder("<!-- 未能找到 banner 数据！ -->\n");
		}

		BannerData config = ComponentUtil.getConfig(banner.getSbanner().getConfig(), BannerData.class);
		if (config == null || banner.getSbanner().getId() == null) {
			return new StringBuilder("<!-- 未能解析 banner 数据！bannerId: " + banner.getSbanner().getId() + " -->\n");
		}

		int displayMode = config.getDisplayMode();

		if (displayMode == 1 && surface) {
			return surfaceRender(banner, config);
		} else if (displayMode == 2) {
			Short isShow = banner.getSbanner().getIsShow();
			if (isShow == null || isShow.shortValue() == (short) 0) {
				return new StringBuilder("<!-- 找到的 banner 数据，设置了隐藏！ -->\n");
			}
			// 视频Banner，通过服务端渲染
			return videoRender(banner, config);
		}

		return render(banner, config);

	}

	/**
	 * 通过 surface 的数据方式渲染
	 * 
	 * @param banner
	 * @param config
	 * @return
	 */
	public StringBuilder videoRender(Banner banner, BannerData config) {
		// 引入的模板
		String theme = "banner_video";
		List<BannerItemQuote> videoBannerItemQuote = banner.getVideoBannerItemQuote();
		if (CollUtil.isEmpty(videoBannerItemQuote)) {
			return new StringBuilder("<!-- banner (videoBannerItemQuote empty) -->\n");
		}

		BannerItemQuote bannerItemQuote = videoBannerItemQuote.get(0);
		HRepertory videoHRepertory = bannerItemQuote.getRepertoryQuote().getHRepertory();
		if (videoHRepertory == null) {
			return new StringBuilder("<!-- banner (videoHRepertory null) -->\n");
		}
		String videoSrc = siteUrlComponent.getVideoSrc(videoHRepertory);

		BannerDataVideoConfig videoConfig = config.getVideoConfig();
		String height = videoConfig.getHeight();

		String userAgent = request.getHeader("User-Agent");
		boolean mobileDevice = UserAgentUtil.isMobileDevice(userAgent);

		String videoStyle = "style=\"height:" + height + ";\"";
		String videoControls = "";
		if (mobileDevice) {
			videoStyle = "";
			videoControls = "controls=\"controls\"";
		}

		String id = "banner-id-" + DigestUtils.md5DigestAsHex(String.valueOf(banner.getSbanner().getId()).getBytes());
		String mapId = "map-" + SecureUtil.md5(id + Math.random());

		VelocityContext ctx = new VelocityContext();
		// 显示文字还是显示图片
		ctx.put("videoSrc", videoSrc);
		ctx.put("mapId", mapId);
		ctx.put("videoStyle", videoStyle);
		ctx.put("videoControls", videoControls);

		Template t = getTemplate(theme);
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);

		return new StringBuilder("<!-- banner -->\n" + sw.toString());
	}

	/**
	 * 通过 surface 的数据方式渲染
	 * 
	 * @param banner
	 * @param config
	 * @return
	 */
	public StringBuilder surfaceRender(Banner banner, BannerData config) {
		// 引入的模板
		String theme = "surface_render";
		List<BannerImageList> imageList = new ArrayList<BannerImageList>();
		
		if(banner.getSbanner().getIsShow() == 0) {
			return new StringBuilder("<!-- not show banner -->\n");
		}

		Iterator<BannerItemQuote> iterator = banner.getImageBannerItemQuote().iterator();
		while (iterator.hasNext()) {
			BannerImageList bannerImageList = new BannerImageList();
			BannerItemQuote next = iterator.next();
			SBannerItem sbannerItem = next.getSbannerItem();
			RepertoryQuote repertoryQuote = next.getRepertoryQuote();
			String configSBannerItem = sbannerItem.getConfig();
			HRepertory hRepertory = repertoryQuote.getHRepertory();

			LinkConfig imglink = StrUtil.isBlank(configSBannerItem) ? null : ComponentUtil.getConfig(configSBannerItem, LinkConfig.class);
			if (imglink == null) {
				imglink = new LinkConfig("", "");
			}

			String src = siteUrlComponent.getImgEmptySrc();
			if (hRepertory != null) {
				src = siteUrlComponent.getImgSrc(hRepertory);
			}
			String title = "";
			String alt = "";
			SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
			if (sRepertoryQuote != null) {
				String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
				if (StringUtils.hasText(sRepertoryQuoteConfig)) {
					ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
					String imageConfigTitle = imageConfig.getTitle();
					if (StringUtils.hasText(imageConfigTitle)) {
						title = imageConfigTitle;
					}
					String imageConfigAlt = imageConfig.getAlt();
					if (StringUtils.hasText(imageConfigAlt)) {
						alt = imageConfigAlt;
					}
				}
			}

			bannerImageList.setAlt(alt).setTitle(title).setSrc(src);
			bannerImageList.setImglink(imglink);

			imageList.add(bannerImageList);
		}
		config.setImageList(imageList);

		VelocityContext ctx = new VelocityContext();
		// 显示文字还是显示图片
		ctx.put("bannerConfig", config);

		Template t = getTemplate(theme);
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);

//		if (config.getTheme().equals("1")) {
//			sRHeadDynamicSource.jsAddBxslider();
//		} else if (config.getTheme().equals("2")) {
//			sRHeadDynamicSource.jsAddSwiper();
//		} else if (config.getTheme().equals("3")) {
//			sRHeadDynamicSource.jsAddSlider();
//		} else if (config.getTheme().equals("4")) {
//			sRHeadDynamicSource.jsAddHtml5zoo();
//		}

		return new StringBuilder("<!-- banner -->\n" + sw.toString());
	}

	/**
	 * 正常通过 html 渲染
	 * 
	 * @param banner
	 * @param config
	 * @return
	 */
	public StringBuilder render(Banner banner, BannerData config) {
		// 唯一id
		String md5Id = DigestUtils.md5DigestAsHex(String.valueOf(banner.getSbanner().getId()).getBytes());
		String id = "banner-id-" + md5Id;

		// 引入的模板
		String theme = "banner" + (banner.getSbanner().getEquip().shortValue() == (short) 1 ? "_pc_" : "_wap_") + config.getTheme();
		if (config.getTheme().equals("2")) {
			theme = theme + "_" + config.getSwiper().getTheme();
		}

		List<BannerImageList> imageList = new ArrayList<BannerImageList>();
		if (banner.getImageBannerItemQuote().size() == 1) {
			theme = "single";
		}
		Iterator<BannerItemQuote> iterator = banner.getImageBannerItemQuote().iterator();
		while (iterator.hasNext()) {
			BannerImageList bannerImageList = new BannerImageList();
			BannerItemQuote next = iterator.next();
			SBannerItem sbannerItem = next.getSbannerItem();
			RepertoryQuote repertoryQuote = next.getRepertoryQuote();
			String configSBannerItem = sbannerItem.getConfig();
			HRepertory hRepertory = repertoryQuote.getHRepertory();

			LinkConfig imglink = ComponentUtil.getConfig(configSBannerItem, LinkConfig.class);
			if (imglink == null) {
				imglink = new LinkConfig("", "");
			}

			String src = siteUrlComponent.getImgEmptySrc();
			if (hRepertory != null) {
				src = siteUrlComponent.getImgSrc(hRepertory);
			}
			String title = "";
			String alt = "";
			SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
			if (sRepertoryQuote != null) {
				String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
				if (StringUtils.hasText(sRepertoryQuoteConfig)) {
					ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
					String imageConfigTitle = imageConfig.getTitle();
					if (StringUtils.hasText(imageConfigTitle)) {
						title = imageConfigTitle;
					}
					String imageConfigAlt = imageConfig.getAlt();
					if (StringUtils.hasText(imageConfigAlt)) {
						alt = imageConfigAlt;
					}
				}
			}

			bannerImageList.setAlt(alt).setTitle(title).setSrc(src);
			bannerImageList.setImglink(imglink);

			imageList.add(bannerImageList);
		}
		config.setImageList(imageList);

		VelocityContext ctx = new VelocityContext();
		// 显示文字还是显示图片
		ctx.put("bannerConfig", config);
		ctx.put("id", id);

		Template t = getTemplate(theme);
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);

		if (config.getTheme().equals("1")) {
			sRHeadDynamicSource.jsAddBxslider();
		} else if (config.getTheme().equals("2")) {
			sRHeadDynamicSource.jsAddSwiper();
		} else if (config.getTheme().equals("3")) {
			sRHeadDynamicSource.jsAddSlider();
		} else if (config.getTheme().equals("4")) {
			sRHeadDynamicSource.jsAddHtml5zoo();
		}

		return new StringBuilder("<!-- banner -->\n" + sw.toString());
	}

	public Template getTemplate(String theme) {
		return basicUdin.getTemplate(name, theme);
	}

}
